import React, { Component } from 'react'
import { NavBar, Icon } from 'antd-mobile'

import './index.scss'
import request from '../../utils/request'
import { getCurrCity } from '../../utils/map'

export class City extends Component {

  state = {
    cityObjects: {}
  }

  componentDidMount () {
    this.getCityData()
  }

  async getCityData () {
    const { data: allCity } = await request.get('/area/city?level=1')
    const { data: hotCity } = await request.get('/area/hot')
    const currCity = await getCurrCity()
    const cityObjects = {}
    // 追加当前城市
    cityObjects['#'] = [currCity]
    // 追加热门城市
    cityObjects['hot'] = hotCity.body
    // 追加其他城市
    for (let i = 97; i <= 122; i++) {
      cityObjects[String.fromCharCode(i)] = []
    }
    allCity.body.forEach(city => {
      const firstLetter = city.pinyin.substr(0, 1)
      cityObjects[firstLetter].push(city)
    });
    this.setState({ cityObjects })
  }

  async resetCurrCity () {
    const currCity = await getCurrCity(true)
    this.setState({ cityObjects: { ...this.state.cityObjects, '#': [currCity] } })
  }

  getCityHeader (key) {
    if (key === '#') {
      return <span>当前城市   [<b style={{fontWeight:'normal'}} onClick={() => this.resetCurrCity()}>刷新</b>]</span>
    }
    if (key === 'hot') {
      return <span>热门城市</span>
    }
    return <span>{key.toUpperCase()}</span>
  }

  render () {
    return (
      <div className="zf-city">
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => this.props.history.go(-1)}
        >城市选择</NavBar>
        {/* 列表 */}
        <div className="list">
          {Object.keys(this.state.cityObjects).map(key => {
            return this.state.cityObjects[key].length !== 0 && <div className="item" key={key}>
              <div className="header">{this.getCityHeader(key)}</div>
              {this.state.cityObjects[key].map(section => {
                return <div className="section" key={section.value}>{section.label}</div>
              })}
            </div>
          })}
        </div>
      </div>
    )
  }
}

export default City
